<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 生成条形码数据
 * @author zxj
 * @description
 */
class Api extends CI_Controller {
    private $oauthData = array();
	function __construct() {
		parent::__construct();
        $this->init();
	}

    function init(){
        //地址
        $url = 'https://test.salesforce.com/services/oauth2/token';
        $postData = array(
            'username' => 'xingzhao@dhht.com.dhht',
            'password' => 'Letmein123',
            'grant_type'=>'password',
            'client_id'=>'3MVG9e2mBbZnmM6lb8fIwTwuhZu5bR8DgTEWhJ9AANdF9d.FJDUJa0QVSZ1AB.0x5.JRPSaHmLTF.i8u3QM0l',
            'client_secret'=>'1669162851177578430',
        );
        //返回认证Token值
        try{
            $this->oauthData = $this->vpost($url,$postData);
            $this->oauthData = json_decode($this->oauthData,true);
        }catch(Exception $e){
            show_error('sign-in error:'.$e->getMessage());
        }
        if(!$this->oauthData['access_token']){
            show_error('getTokenFailure:'.$this->oauthData['access_token']);
        }
    }


    /**
     * 接口一
     * 推送订单主信息和详细信息
     */
    function oms_to_sf001(){
        $url = $this->oauthData['instance_url'].'/services/apexrest/I_OMS_SF_001';
        $headers = array();
        $headers[] = 'Authorization:Bearer '.$this->oauthData['access_token'];
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $orders = array(
            'oms_order'=>array(
                'OMSOrderID__c'=>'es00007146',
                'CustomerNum__c'=>'c0001',
                'MerchantCustomerNum__c'=>'MER00000001',
                'CustomerType__c'=>'Individual User',
                'CustomerAddress__c'=>'Manuel Martínez Ayegui Murchante,2 3b Tudela Navarra 31500 Spain ,Navarra,,ES,31500',
                'CustomerNameText__c'=>'Manuel Martínez Ayegui',
                'CustomerPhone__c'=>'689547691',
                'CustomersEmail__c'=>'dhhtamz@outlook.com',
                //价格
                'CurrencyIsoCode'=>'CNY', //货币种类
                'DiscountAmount__c'=>'168.00', //折扣总额
                'DiscountAmountBrand__c'=>'68.00', //品牌折扣总额
                'DiscountAmountIndividualUser__c'=>'100.00', //个人折扣总额
                'DiscountAmountMerchant__c'=>'100.00', //商家折扣总额
                'GrandTotal__c'=>'168.00', //总额
                'GrandTotalBrand__c'=>'68.00', //品牌总额
                'GrandTotalIndividualUser__c'=>'100.00', //个人总额
                'GrandTotalMerchant__c'=>'100.00', //商家总额
                'OrderSubtotal__c'=>'168.00', //订单小记总额
                'OrderSubtotalBrand__c'=>'68.00', //订单品牌小记总额
                'OrderSubtotalIndividualUser__c'=>'100.00', //订单个人小记总额
                'OrderSubtotalMerchant__c'=>'100.00', //订单商家总额
                //包裹信息
                'OpenPackageQC__c'=>'开包质检信息',
                'OrderSource__c'=>'tomrepair.es',
                'Remark__c'=>'sku68464 a0221806A AM0001361 solution: for second hand; 收到入库； problem: 客人收到不要了，手机全新； the reason for return is that customer does not want it any more, he thinks the phone is too big; the phone is brand new',
                'RepairCenter__c'=>'Spain',
                'ServiceType__c'=>'refurbish',
                'ShipinTrack__c'=>'T00001',
                'ShipoutTrack__c'=>'T-OUT00001',
                'ShippingFee__c'=>'15.00', //总运费
                'ShippingFeeBrand__c'=>'0.00', //品牌运费
                'ShippingFeeIndividualUser__c'=>'10.00', //个人运费
                'ShippingFeeMerchant__c'=>'10.00', //商家运费
                'SourceNumber__c'=>'150003748', //来源单号
                'Status__c'=>'Waiting for receive', //订单状态
                'SupplementAmount__c'=>'33.2', //补充金额
                'SupplementAmountBrand__c'=>'33.2', //品牌补充金额
                'SupplementAmountIndividualUser__c'=>'33.2', //个人补充金额
                'SupplementAmountMerchant__c'=>'33.2', //商家补充金额
                'Technician__c'=>'z.', //处理人
                'CreationDate__c'=>time(), //订单创建日期
                'WebsiteOrigin__c'=>'pandaClever',
                'RepairOrderProductID__c'=>'', //如果返修单传上次的维修单号
            ),
            'oms_details'=>array(
                array(
                    'OMSParentID__c'=>'es00007146',
                    'OMSID__c'=>'P00001',
                    'AcceptQuotation__c'=>'',  //是否需要接受报价 yes no null
                    'NeedToConfirm__c'=>'Yes',  //是否需要确认报价
                    'Accessories__c'=>'附件A,附件B',
                    'InWarranty__c'=>'Yes', //质保类型
                    'BrandCustomerNum__c'=>'BRD00000001',
                    'Category__c'=>'Scooter', //产品类型
                    'CSRemark__c'=>'sku68464 a0221806A AM0001361 solution: for second hand; 收到入库； problem: 客人收到不要了，手机全新； the reason for return is that customer does not want it any more, he thinks the phone is too big; the phone is brand new; ', //客服质检备注
                    'CustomerRemark__c'=>'客户备注',
                    'DescriptionConsistent__c'=>'Yes',
                    'ExitQC__c'=>'质检报告',
                    'Fault__c'=>'Photo blur;Cant focus',
                    'IMEI__c'=>'354376070879941',
                    //产品价格
                    'BrandSubTotal__c'=>'22.50',
                    'IndividualUserSubTotal__c'=>'22.50',
                    'MerchantSubTotal__c'=>'22.50',
                    'LaborAmountBrand__c'=>'22.50',
                    'LaborAmountIndividualUser__c'=>'22.50',
                    'LaborAmountMerchant__c'=>'22.50',
                    'NAQAmount__c'=>'22.50', //不接受报价金额
                    'PartsAmountBrand__c'=>'22.50',
                    'PartsAmountIndividualUser__c'=>'22.50',
                    'PartsAmountMerchant__c'=>'22.50',
                    'PhotosURL1__c'=>'http://oms.tomrepair.es/resource/images/index.jpg',
                    'PhotosURL2__c'=>'http://oms.tomrepair.es/resource/images/index.jpg',
                    'PhotosURL3__c'=>'http://oms.tomrepair.es/resource/images/index.jpg',
                    'PhotosURL4__c'=>'http://oms.tomrepair.es/resource/images/index.jpg',
                    'PhotosURL5__c'=>'http://oms.tomrepair.es/resource/images/index.jpg',
                    'PhotosURL6__c'=>'http://oms.tomrepair.es/resource/images/index.jpg',
                    'PhysicalAppearance__c'=>'brand new', //成色
                    'PictureURL__c'=>'', //?留着
                    'ProductSKUText__c'=>'00000001',
                    'Quantity__c'=>'1',
                    'RepairItem__c'=>'Replace the big mirror;Replace the headset plug',
                    'Status__c'=>'quoted',
                    'SupplementAmount__c'=>'33.5',
                    'Technician__c'=>'Z.',
                    'TechnicianRemark__c'=>'更换卡槽什么的...',
                    'DefectDes__c'=>'故障描述好像也没有',
                ),
            )
        );
        $orders = json_encode($orders);
        try{
            $result = $this->vpost($url,$orders,$headers);
        }catch (Exception $e){
            show_error('oms_to_sf001 error:'.$e->getMessage());
        }
        $result = json_decode($result,true);
        gsh_output($result);
    }



    /**
     * 接口二
     * 推送订单主表状态
     */
    function oms_to_sf002(){
        $url = $this->oauthData['instance_url'].'/services/apexrest/I_OMS_SF_002';
        $headers = array();
        $headers[] = 'Authorization:Bearer '.$this->oauthData['access_token'];
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $orders = array(
            'oms_order'=>array(
                'OMSOrderID__c'=>'es00007146',
                'Status__c'=>'testing',
            )
        );
        $orders = json_encode($orders);
        try{
            $result = $this->vpost($url,$orders,$headers);
        }catch (Exception $e){
            show_error('oms_to_sf002 error:'.$e->getMessage());
        }
        $result = json_decode($result,true);
        gsh_output($result);
    }


    /**
     * 接口三
     * 推送产品明细信息
     */
    function oms_to_sf003()
    {
        $url = $this->oauthData['instance_url'] . '/services/apexrest/I_OMS_SF_003';
        $headers = array();
        $headers[] = 'Authorization:Bearer ' . $this->oauthData['access_token'];
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $orders = array(
            'oms_order_detail' => array(
                'OMSParentID__c' => 'es00007146',
                'OMSID__c' => 'P00001',
                'AcceptQuotation__c' => '',
                'NeedToConfirm__c' => 'Yes',
                'BrandCustomerNum__c' => 'BRD00000001',
                'BrandSubTotal__c' => '25.20',
                'Category__c' => 'Scooter',
                'CSRemark__c' => 'testtest',
                'CustomerRemark__c' => '...',
                'DescriptionConsistent__c' => '....',
                'ExitQC__c' => '...?',
                'Fault__c' => '...?',
                'IMEI__c' => '...?',
                //费用
                'InWarranty__c' => 'Y', //质保类型
                'IndividualUserSubTotal__c' => '25.55',
                'LaborAmountBrand__c' => '26.99',
                'LaborAmountIndividualUser__c' => '26.99',
                'LaborAmountMerchant__c' => '26.99',
                'MerchantSubTotal__c' => '26.99',
                'NAQAmount__c' => '26.99',
                'PartsAmountBrand__c' => '26.99',
                'PartsAmountIndividualUser__c' => '26.99',
                'PartsAmountMerchant__c' => '26.99',
                'PhotosURL__c' => '26.99',
                'PhysicalAppearance__c' => '26.99',
                'PictureURL__c' => '26.99',
                'ProductSKUText__c' => '26.99',
                'Quantity__c' => '26.99',
                'RepairItem__c' => '26.99',
                'Status__c' => '26.99',
                'SupplementAmount__c' => '26.99',
                'Technician__c' => '26.99',
                'TechnicianRemark__c' => '26.99',
                'TotalAmount__c' => '26.99',
                'DefectDes__c' => '26.99',
            ),
            'oms_defect_details' => array(
                array(
                    'OMSParentID__c' => 'P10001',
                    'OMSID__c' => '123456',
                    'RepairItem__c' => 'disassamble the device',
                    'Remark__c' => 'disassamble the device',
                ),
            ),
            'oms_parts_list' => array(
                array(
                    'OMSParentID__c' => 'P10001',
                    'OMSID__c' => '23655',
                    'ProductSKUText__c' => '00000022',
                ),
            ),
            'oms_quotes' => array(
                array(
                    'OMSParentID__c' => 'P10001',
                    'OMSID__c' => 'QUT00000001',
                    'Amount__c' => '77.55',
                    'ProductSKUText__c' => '00000046',
                    'Remark__c' => '00000046',
                ),
            )
        );
        $orders = json_encode($orders);
        try{
            $result = $this->vpost($url,$orders,$headers);
        }catch (Exception $e){
            show_error('oms_to_sf003 error:'.$e->getMessage());
        }
        $result = json_decode($result,true);
        gsh_output($result);
    }




    /**
     * 接口四
     * 推送订单产品状态
     */
    function oms_to_sf004(){
        $url = $this->oauthData['instance_url'].'/services/apexrest/I_OMS_SF_004';
        $headers = array();
        $headers[] = 'Authorization:Bearer '.$this->oauthData['access_token'];
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $orders = array(
            'oms_order_detail'=>array(
                'OMSID__c'=>'P10001',
                'Status__c'=>'Price Quoted',
            )
        );
        $orders = json_encode($orders);
        $result = $this->vpost($url,$orders,$headers);
        $result = json_decode($result,true);
        gsh_output($result);
    }



    /**
     * 接口五
     * 接受报价数据
     * '[{"isSubmit":false,"OMSIDS__c":[{"RDT73257815":"Yes","RDT70358136":null,"RDT70134126":null}],"OMSOrderID__c":"REP69428165","token":"A367FB69926E0CB863968A4E14011877"}]'
     * Yes/null/No
     */
    function sf_to_oms005(){
        //$gpData = gp();
        $gpData = @file_get_contents('php://input');
        $gpData = json_decode($gpData,true);
        log_output($gpData);
        if(!$gpData){
            json_output('','未接受到数据',false);
        }
        if($gpData['token']!='A367FB69926E0CB863968A4E14011877'){
            json_output('','token error',false);
        }
        json_output($gpData,'返回成功!',true);
    }



    /**
     * 接口六
     * 充值扣款接口
     */
    function oms_to_sf006(){
        $url = $this->oauthData['instance_url'].'/services/apexrest/I_OMS_SF_006';
        $headers = array();
        $headers[] = 'Authorization:Bearer '.$this->oauthData['access_token'];
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $orders = array(
            'oms_balance'=>array(
                'OMSID__c'=>'de00000203',
                'OMSOrderID__c'=>'P10001',
                'Amount__c'=>'11.2', //金额
                'Balance__c'=>'32.5', //存款余额
                'CustomerNum__c'=>'c00001', //客户编号
                'CurrencyIsoCode'=>'CNY', //货币种类
                'DateLong__c'=>'1462731319',
                'Type__c'=>'Charge', //Charge|Deposit
            )
        );
        $orders = json_encode($orders);
        $result = $this->vpost($url,$orders,$headers);
        $result = json_decode($result,true);
        gsh_output($result);
    }


    /**
     * 接口七
     * 分包裹接口
     */
    function oms_to_sf007(){
        $url = $this->oauthData['instance_url'].'/services/apexrest/I_OMS_SF_007';
        $headers = array();
        $headers[] = 'Authorization:Bearer '.$this->oauthData['access_token'];
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $orders = array(
            'oms_shippment'=>array(
                'ShippmentID__c'=>'dhht0085', //追踪号
                'OMSParentID__c'=>'de00000203',
                'OMSDetailIDs__c'=>'22,58,10', //产品ids 1,2,3,.....
            )
        );
        $orders = json_encode($orders);
        $result = $this->vpost($url,$orders,$headers);
        $result = json_decode($result,true);
        gsh_output($result);
    }


    /**
     * 接口八
     * 分包裹接口
     */
    function oms_to_sf008(){
        $url = $this->oauthData['instance_url'].'/services/apexrest/I_OMS_SF_008';
        $headers = array();
        $headers[] = 'Authorization:Bearer '.$this->oauthData['access_token'];
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $orders = array(
            'oms_shippment'=>array(
                'ShippmentID__c'=>'dhht0085', //追踪号
                'OMSParentID__c'=>'de00000203',
                'OMSDetailIDs__c'=>'22,58,10', //产品ids 1,2,3,.....
            )
        );
        $orders = json_encode($orders);
        $result = $this->vpost($url,$orders,$headers);
        $result = json_decode($result,true);
        gsh_output($result);
    }








    /**
     * 模拟提交数据函数
     * @param $url
     * @param $data
     * @param array $headers
     * @return mixed
     */
    function vpost($url, $data, $headers = array())
    {
        $curl = curl_init(); // 启动一个CURL会话
        if($headers && is_array($headers)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $tmpInfo; // 返回数据
    }








    function get_system_date($is_system = ''){
        if(!$is_system){
            //date_default_timezone_set('Etc/GMT+8');
            //date_default_timezone_set('Asia/shanghai');
            date_default_timezone_set('PRC');
        }
        gsh_output(date('Y-m-d H:i:s'));
    }



    function index(){
        $this->load->library('barcode');
        $wsdl_url = 'http://192.168.10.103:8889/webService/GetNewSkuForBackPieces.php?wsdl';
        $soap = new SoapClient(null,array('location'=>$wsdl_url,'uri'=>'GetNewSkuForBackPieces'));
        $sku='sku3980';
        $getInventoryRs = $soap->getBackPiecesSku('maintain','maintain_sys',$sku,'7成新');
        var_dump($getInventoryRs);
        echo $this->barcode->getBarcodeHTML($sku,"C128",1,30,'black','title?');
    }


    function testPrint(){
        $this->output->enable_profiler(FALSE);
        $this->load->library('barcode');
        $barcodeList = array();
        $barcodeItem['barcode'] = $this->barcode->getBarcodeHTML('z. 222',"C128");
        $barcodeList[0] = $barcodeItem;
        $barcodeItem['barcode'] = $this->barcode->getBarcodeHTML('sku1234567898',"C128");
        $barcodeList[1] = $barcodeItem;
        $barcodeItem['barcode'] = $this->barcode->getBarcodeHTML('April 123456',"C128");
        $barcodeList[2] = $barcodeItem;
        $data['barcodeList'] = $barcodeList;
        $this->load->view('defaults/testPrint_view',$data);
    }

    function inpart(){
        $str = '';
        foreach (explode(PHP_EOL,$str) as $val) {
            list($sc,$en) =  explode('|',$val);
            $newPart[trim($sc)] = trim($en);
        }

        gsh_output($newPart);
        foreach ($newPart as $key=>$val) {
            $indata = array(
                'maintain_part_name'=>$key,'maintain_part_name_en'=>$val,
                'maintain_part_grade'=>3,'sort_id'=>2
                );
            $this->common_model->insert('maintain_part',$indata);
        }

    }


    function annaData(){
        for($i=0;$i<23;$i++) {
            //生成维修单号
            $oid = $this->order_model->createRepairId('4');
            $orderInfo['maintain_id'] = $oid;
            $orderInfo['repair_site_id'] = 4;
            $orderInfo['status_id'] = 2;
            $orderInfo['consumer_name'] = '触动力';
            $orderInfo['consumer_address'] = '触动力';
            $orderInfo['consumer_email'] = 'chudongli@chudongli.com';
            $orderInfo['consumer_phone'] = '86';
            $orderInfo['maintain_type_id'] = '6';
            $orderInfo['maintain_type_id'] = '6';
            $this->order_model->addOrSetOrder($orderInfo);
            //添加产品
            $productInfo['maintain_id'] = $oid;
            $productInfo['sort_id'] = 3;
            $productInfo['sku'] = 'sku68377';
            $productInfo['color'] = '红色';
            $productInfo['size'] = '6.5';
            $productInfo['is_bluetooth'] = '0';
            $productInfo['is_yaokong'] = '0';
            $productInfo['damage_id'] = '1';
            $pid = $this->product_model->addOrSetProduct($productInfo);
            //添加质检报告
            $qcInfo['oid'] = $oid;
            $qcInfo['pid'] = $pid;
            $qcInfo['is_description'] = 1;
            $qcInfo['damage'] = '全新';

            $this->common_model->insert('maintain_qcreport',$qcInfo);
            gsh_output('oid:'.$oid.'****pid:'.$pid);
        }
    }





}
